<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>数据图表 - 御物联</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        :root{
            --primary:#409EFF;
            --stage-bg:#EDE3D3; /* 全屏舞台背景（如截图外层米色） */
            --bg:#F5F7FA;      /* 页面内部背景（卡片外层浅灰） */
            --text:#303133;
            --subtext:#909399;
            --card:#FFFFFF;
            --border:#EBEEF5;
            --ok:#67C23A;
            --warn:#E6A23C;
            --danger:#F56C6C;
        }
        body{ font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif; background:var(--stage-bg); color:var(--text); }

        /* 页面容器，限制移动端阅读宽度并居中 */
        .page{ min-height:100vh; padding-bottom:calc(72px + env(safe-area-inset-bottom)); max-width:480px; margin:0 auto; background:var(--bg); }

        /* 页头样式 */
        .header-box{ position:sticky; top:0; z-index:20; background:var(--card); border-bottom:1px solid var(--border); box-shadow:0 -2px 8px rgba(0,0,0,.04); padding:0; display:flex; flex-direction:column; align-items:stretch; margin:0; border-radius:0; }
        .header-top{ display:flex; align-items:center; justify-content:space-between; padding:8px 12px; background:var(--card); gap:8px; }
        .header-title{ text-align:center; font-size:16px; font-weight:600; color:var(--primary); line-height:1.4; padding:10px 12px; background:rgba(245,247,250,0.6); }
        .user{ margin-left:auto; padding:0 10px; height:32px; border-radius:16px; background:var(--card); border:1px solid var(--border); display:flex; align-items:center; gap:8px; color:var(--text); box-shadow:0 1px 3px rgba(0,0,0,.03); cursor:pointer; }
        .user-avatar{ width:22px; height:22px; border-radius:50%; background:var(--primary); color:#fff; display:flex; align-items:center; justify-content:center; font-size:12px; }

        /* 返回按钮 */
        .back-btn{ display:flex; align-items:center; gap:6px; padding:0; color:var(--text); text-decoration:none; font-size:14px; height:32px; background:none; border:none; cursor:pointer; }
        .back-btn:hover{ color:var(--primary); }
        .back-icon{ font-size:16px; }
        
        /* 设备信息卡片 */
        .device-info-card{ background:var(--card); margin:12px; border-radius:12px; padding:16px; box-shadow:0 2px 6px rgba(0,0,0,.03); border:1px solid var(--border); }
        .device-info-text{ font-size:15px; color:var(--text); line-height:1.6; text-align:center; }
        .device-info-text .device-name{ font-weight:600; color:var(--primary); }
        .device-info-text .sensor-name{ color:var(--subtext); margin:0 4px; }
        .device-info-text .current-value{ font-weight:600; color:var(--primary); }
        
        /* 时间周期选择 */
        .time-period-card{ background:var(--card); margin:0 12px 12px; border-radius:12px; padding:16px; box-shadow:0 2px 6px rgba(0,0,0,.03); border:1px solid var(--border); }
        .period-title{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:12px; }
        .period-buttons{ display:flex; gap:8px; flex-wrap:wrap; }
        .period-btn{ background:var(--bg); color:var(--text); border:1px solid var(--border); border-radius:8px; padding:8px 16px; font-size:13px; cursor:pointer; transition:all .2s; }
        .period-btn.active{ background:var(--primary); color:#fff; border-color:var(--primary); }
        .period-btn:hover:not(.active){ background:var(--border); }
        
        /* 图表容器 */
        .chart-card{ background:var(--card); margin:0 12px 12px; border-radius:12px; padding:16px; box-shadow:0 2px 6px rgba(0,0,0,.03); border:1px solid var(--border); }
        .chart-title{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:16px; text-align:center; }
        .chart-container{ position:relative; height:300px; width:100%; }
        .chart-loading{ display:flex; align-items:center; justify-content:center; height:300px; color:var(--subtext); font-size:14px; }
        
        /* 数据统计 */
        .stats-card{ background:var(--card); margin:0 12px 12px; border-radius:12px; padding:16px; box-shadow:0 2px 6px rgba(0,0,0,.03); border:1px solid var(--border); }
        .stats-title{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:12px; }
        .stats-grid{ display:grid; grid-template-columns:repeat(2,1fr); gap:12px; }
        .stat-item{ text-align:center; padding:12px; background:var(--bg); border-radius:8px; }
        .stat-value{ font-size:18px; font-weight:600; color:var(--primary); margin-bottom:4px; }
        .stat-label{ font-size:12px; color:var(--subtext); }
        
        /* 抽屉样式 */
        .drawer-mask{ position:fixed; inset:0; background:rgba(0,0,0,.35); opacity:0; pointer-events:none; transition:opacity .25s ease; z-index:999; }
        .drawer-mask.open{ opacity:1; pointer-events:auto; }
        .drawer{ position:fixed; top:0; right:0; height:100vh; width:86vw; max-width:420px; background:var(--card); border-left:1px solid var(--border); box-shadow:-12px 0 24px rgba(0,0,0,.12); transform:translateX(100%); transition:transform .25s ease; z-index:1000; display:flex; flex-direction:column; }
        .drawer.open{ transform:translateX(0); }
        .drawer-header{ display:flex; align-items:center; justify-content:space-between; padding:12px 14px; border-bottom:1px solid var(--border); font-weight:600; }
        .drawer-body{ flex:1; overflow-y:auto; padding:0; }
        .drawer-row{ padding:12px 14px; border-bottom:1px solid var(--border); display:flex; align-items:center; gap:12px; }
        .drawer-row:last-child{ border-bottom:none; }
        .drawer-icon{ width:20px; height:20px; flex-shrink:0; }
        .drawer-text{ flex:1; font-size:14px; color:var(--text); }
        .drawer-arrow{ width:16px; height:16px; opacity:.5; }
        
        /* 提醒弹窗 */
        .alert-modal{ position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background:var(--card); border-radius:12px; padding:20px; box-shadow:0 8px 32px rgba(0,0,0,.15); z-index:1001; max-width:320px; width:90%; text-align:center; border:1px solid var(--border); display:none; opacity:0; transition:opacity 0.3s ease; }
        .alert-modal.show{ display:block; opacity:1; }
        .alert-icon{ font-size:32px; margin-bottom:12px; }
        .alert-title{ font-size:16px; font-weight:600; color:var(--text); margin-bottom:8px; }
        .alert-message{ font-size:14px; color:var(--subtext); line-height:1.5; margin-bottom:16px; }
        .alert-progress{ width:100%; height:3px; background:var(--bg); border-radius:2px; overflow:hidden; }
        .alert-progress-bar{ height:100%; background:var(--primary); border-radius:2px; animation:progress 10s linear forwards; }
        @keyframes progress{ from{ width:0%; } to{ width:100%; } }
        
        /* 响应式设计 */
        @media (max-width:480px){
            .stats-grid{ grid-template-columns:1fr; }
            .period-buttons{ justify-content:center; }
        }
    </style>
</head>
<body>
    <!-- 页面容器 -->
    <div class="page">
        <!-- 页头 -->
        <div class="header-box">
            <div class="header-top">
                <button class="back-btn" id="backBtn">
                    <span class="back-icon">←</span>
                    <span>返回</span>
                </button>
                <div class="user" id="userBtn">
                    <div class="user-avatar" id="userAvatar">U</div>
                    <span id="userName">用户</span>
                </div>
            </div>
            <div class="header-title" id="pageTitle">数据图表</div>
        </div>

        <!-- 页面内容 -->
        <!-- 设备信息卡片 -->
        <div class="device-info-card">
            <div class="device-info-text" id="deviceInfoText">
                <span class="device-name" id="deviceName">设备名称</span>
                <span class="sensor-name" id="sensorName">传感器名称</span>
                <span class="current-value" id="currentValue">--</span>
            </div>
        </div>

        <!-- 时间周期选择 -->
        <div class="time-period-card">
            <div class="period-title">选择时间周期</div>
            <div class="period-buttons">
                <button class="period-btn active" data-period="24h">24小时内</button>
                <button class="period-btn" data-period="3d">3天</button>
                <button class="period-btn" data-period="7d">7天</button>
                <button class="period-btn" data-period="30d">30天</button>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="chart-card">
            <div class="chart-title" id="chartTitle">数据趋势图</div>
            <div class="chart-container">
                <canvas id="dataChart"></canvas>
            </div>
        </div>

        <!-- 数据统计 -->
        <div class="stats-card">
            <div class="stats-title">数据统计</div>
            <div class="stats-grid">
                <div class="stat-item">
                    <div class="stat-value" id="maxValue">--</div>
                    <div class="stat-label">最大值</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="minValue">--</div>
                    <div class="stat-label">最小值</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="avgValue">--</div>
                    <div class="stat-label">平均值</div>
                </div>
       
            </div>
        </div>
    </div>

    <!-- 提醒弹窗 -->
    <div class="alert-modal" id="alertModal">
        <div class="alert-icon">⚠️</div>
        <div class="alert-title">数据加载提醒</div>
        <div class="alert-message">数据量过大，传感器可能会记录每一秒的数据。接口要做好优化，按照不同的统计维度，返回坐标点数为100以内最好，避免卡死或长时间等待。</div>
        <div class="alert-progress">
            <div class="alert-progress-bar"></div>
        </div>
    </div>

    <!-- 用户抽屉 -->
    <div class="drawer-mask" id="drawerMask"></div>
    <div class="drawer" id="userDrawer">
        <div class="drawer-header">
            <span>用户信息</span>
            <button id="closeDrawer" style="background:none;border:none;font-size:18px;cursor:pointer">×</button>
        </div>
        <div class="drawer-body">
            <div class="drawer-row" style="padding:20px 0 12px; text-align:center;">
                <button id="userInfoBtn" class="btn btn-primary" style="width:100%; height:48px; font-size:16px;">查看个人信息</button>
            </div>
            <div class="drawer-row" style="border-bottom:none; padding:12px 0 20px; text-align:center;">
                <button id="controlPanelBtn" class="btn" style="width:100%; height:48px; font-size:16px; background:var(--ok); color:#fff; border-color:var(--ok);">操作面板展示</button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取页面参数
            const urlParams = new URLSearchParams(window.location.search);
            const deviceName = urlParams.get('device') || '未知设备';
            const sensorName = urlParams.get('sensor') || '未知传感器';
            const sensorType = urlParams.get('type') || 'temperature';
            
            // 传感器配置
            const sensorConfigs = {
                temperature: { unit: '°C', color: '#ff6b6b', name: '温度' },
                humidity: { unit: '%', color: '#4ecdc4', name: '湿度' },
                light: { unit: 'lux', color: '#ffe66d', name: '光照度' },
                pm25: { unit: 'μg/m³', color: '#a8e6cf', name: 'PM2.5' },
                pm10: { unit: 'μg/m³', color: '#88d8c0', name: 'PM10' },
                co2: { unit: 'ppm', color: '#ffd93d', name: 'CO2浓度' },
                co: { unit: 'ppm', color: '#6bcf7f', name: 'CO浓度' },
                pressure: { unit: 'hPa', color: '#4d96ff', name: '压力' },
                windSpeed: { unit: 'm/s', color: '#9b59b6', name: '风速' },
                noise: { unit: 'dB', color: '#e74c3c', name: '噪声' },
                waterLevel: { unit: 'm', color: '#3498db', name: '水位' },
                flow: { unit: 'L/min', color: '#2ecc71', name: '流量' },
                voltage: { unit: 'V', color: '#f39c12', name: '电压' },
                current: { unit: 'A', color: '#e67e22', name: '电流' },
                power: { unit: 'W', color: '#d35400', name: '功率' }
            };
            
            const config = sensorConfigs[sensorType] || sensorConfigs.temperature;
            
            // 初始化页面
            initPage();
            
            // 初始化图表
            let chart = null;
            initChart();
            
            // 初始化用户信息
            initUserInfo();
            
            // 显示提醒弹窗
            showAlert();
            
            // 绑定事件
            bindEvents();
            
            function initPage() {
                document.getElementById('deviceName').textContent = deviceName;
                document.getElementById('sensorName').textContent = config.name;
                document.getElementById('pageTitle').textContent = config.name + '图表';
                document.getElementById('chartTitle').textContent = config.name + '趋势图';
                
                // 设置当前值
                const currentValue = generateCurrentValue(sensorType);
                document.getElementById('currentValue').textContent = currentValue + (config.unit || '');
            }
            
            function initUserInfo() {
                // 从localStorage获取用户信息
                const user = JSON.parse(localStorage.getItem('currentUser') || '{}');
                const userAvatar = document.getElementById('userAvatar');
                const userName = document.getElementById('userName');
                if (userAvatar) {
                    userAvatar.textContent = (user.name || 'U').slice(0, 1);
                }
                if (userName) {
                    userName.textContent = user.name || '用户';
                }
            }
            
            function showAlert() {
                const alertModal = document.getElementById('alertModal');
                if (alertModal) {
                    // 显示弹窗
                    alertModal.classList.add('show');
                    
                    // 10秒后自动隐藏
                    setTimeout(() => {
                        alertModal.classList.remove('show');
                    }, 10000);
                }
            }
            
            function initChart() {
                const ctx = document.getElementById('dataChart').getContext('2d');
                const data = generateChartData('24h');
                
                chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: [{
                            label: config.name,
                            data: data.values,
                            borderColor: config.color,
                            backgroundColor: config.color + '20',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.4,
                            pointRadius: 3,
                            pointHoverRadius: 6
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            x: {
                                display: true,
                                title: {
                                    display: true,
                                    text: '时间'
                                },
                                grid: {
                                    color: 'rgba(0,0,0,0.1)'
                                }
                            },
                            y: {
                                display: true,
                                title: {
                                    display: true,
                                    text: config.name + ' (' + config.unit + ')'
                                },
                                grid: {
                                    color: 'rgba(0,0,0,0.1)'
                                }
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index'
                        }
                    }
                });
                
                updateStats(data.values);
            }
            
            function generateChartData(period) {
                const now = new Date();
                let labels = [];
                let values = [];
                let dataPoints = 0;
                
                switch(period) {
                    case '24h':
                        dataPoints = 24;
                        for(let i = 23; i >= 0; i--) {
                            const time = new Date(now.getTime() - i * 60 * 60 * 1000);
                            labels.push(time.getHours() + ':00');
                            values.push(generateValue(sensorType, time));
                        }
                        break;
                    case '3d':
                        dataPoints = 72;
                        for(let i = 71; i >= 0; i--) {
                            const time = new Date(now.getTime() - i * 60 * 60 * 1000);
                            labels.push(time.getMonth() + 1 + '/' + time.getDate() + ' ' + time.getHours() + ':00');
                            values.push(generateValue(sensorType, time));
                        }
                        break;
                    case '7d':
                        dataPoints = 28;
                        for(let i = 27; i >= 0; i--) {
                            const time = new Date(now.getTime() - i * 6 * 60 * 60 * 1000);
                            labels.push(time.getMonth() + 1 + '/' + time.getDate() + ' ' + time.getHours() + ':00');
                            values.push(generateValue(sensorType, time));
                        }
                        break;
                    case '30d':
                        dataPoints = 30;
                        for(let i = 29; i >= 0; i--) {
                            const time = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
                            labels.push(time.getMonth() + 1 + '/' + time.getDate());
                            values.push(generateValue(sensorType, time));
                        }
                        break;
                }
                
                return { labels, values };
            }
            
            function generateValue(type, time) {
                const baseValues = {
                    temperature: 25,
                    humidity: 60,
                    light: 500,
                    pm25: 35,
                    pm10: 50,
                    co2: 400,
                    co: 5,
                    pressure: 1013,
                    windSpeed: 3,
                    noise: 45,
                    waterLevel: 1.5,
                    flow: 10,
                    voltage: 220,
                    current: 5,
                    power: 1100
                };
                
                const ranges = {
                    temperature: 15,
                    humidity: 30,
                    light: 1000,
                    pm25: 50,
                    pm10: 80,
                    co2: 200,
                    co: 10,
                    pressure: 50,
                    windSpeed: 10,
                    noise: 20,
                    waterLevel: 2,
                    flow: 20,
                    voltage: 40,
                    current: 10,
                    power: 500
                };
                
                const base = baseValues[type] || 25;
                const range = ranges[type] || 15;
                
                // 添加时间相关的波动
                const hour = time.getHours();
                const day = time.getDate();
                const timeFactor = Math.sin(hour * Math.PI / 12) * 0.3 + Math.sin(day * Math.PI / 15) * 0.2;
                const randomFactor = (Math.random() - 0.5) * 0.4;
                
                return Math.round((base + range * (timeFactor + randomFactor)) * 10) / 10;
            }
            
            function generateCurrentValue(type) {
                return generateValue(type, new Date());
            }
            
            function updateStats(values) {
                const max = Math.max(...values);
                const min = Math.min(...values);
                const avg = values.reduce((a, b) => a + b, 0) / values.length;
                
                document.getElementById('maxValue').textContent = max.toFixed(1);
                document.getElementById('minValue').textContent = min.toFixed(1);
                document.getElementById('avgValue').textContent = avg.toFixed(1);
            }
            
            function bindEvents() {
                // 返回按钮
                document.getElementById('backBtn').addEventListener('click', function() {
                    history.back();
                });
                
                // 时间周期按钮
                document.querySelectorAll('.period-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        // 更新按钮状态
                        document.querySelectorAll('.period-btn').forEach(b => b.classList.remove('active'));
                        this.classList.add('active');
                        
                        // 更新图表数据
                        const period = this.dataset.period;
                        const data = generateChartData(period);
                        
                        chart.data.labels = data.labels;
                        chart.data.datasets[0].data = data.values;
                        chart.update();
                        
                        updateStats(data.values);
                    });
                });
                
                // 用户抽屉
                const drawer = document.getElementById('userDrawer');
                const mask = document.getElementById('drawerMask');
                const userBtn = document.getElementById('userBtn');
                const closeDrawer = document.getElementById('closeDrawer');
                
                function openDrawer() {
                    drawer.classList.add('open');
                    mask.classList.add('open');
                }
                
                function closeDrawerFunc() {
                    drawer.classList.remove('open');
                    mask.classList.remove('open');
                }
                
                userBtn.addEventListener('click', openDrawer);
                closeDrawer.addEventListener('click', closeDrawerFunc);
                mask.addEventListener('click', closeDrawerFunc);
                
                // 个人信息按钮
                document.getElementById('userInfoBtn').addEventListener('click', function() {
                    closeDrawerFunc();
                    location.href = 'user-info.html';
                });
                
                // 操作面板按钮
                document.getElementById('controlPanelBtn').addEventListener('click', function() {
                    closeDrawerFunc();
                    location.href = 'control-panel-demo.html';
                });
                
                // Esc 关闭抽屉
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape') closeDrawerFunc();
                });
            }
        });
    </script>
</body>
</html>
